﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using P2.Cuberry.Framework.Helper;
using System.Collections.ObjectModel;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Modules.SimpleAccounting.FiTransaction.DAL;
using P2.Cuberry.Framework.BOLBase;
using System.Transactions;
using P2.Cuberry.Framework.Security;

namespace P2.Cuberry.Modules.SimpleAccounting.FiTransaction.BusinessEntities
{
    class FiChequeToFiTransactionItem : BizObject, INotifyPropertyChanged
    {

        #region TemporaryStorage
        public static List<FiChequeToFiTransactionItem> TemporaryStorage = new List<FiChequeToFiTransactionItem>();
        #endregion


        #region Members

        //++KeyID
        int _fiChequeID = -1;
        public int FiChequeID
        {
            get { return _fiChequeID; }
            protected set
            {
                if (_fiChequeID != value)
                {
                    _fiChequeID = value;
                }
            }
        }

        //Add++
        int _fiscalYearID = -1;
        public int FiscalYearID
        {
            get { return _fiscalYearID; }
            set
            {
                if (value != _fiscalYearID)
                {
                    _fiscalYearID = value;
                    Modified = true;
                }
            }
        }

        int _FiTransactionItemID = 0;
        public int FiTransactionItemID
        {
            get { return _FiTransactionItemID; }
            set
            {
                if (value != _FiTransactionItemID)
                {
                    _FiTransactionItemID = value;
                    Modified = true;
                }
            }
        }


        DateTime? _CreatedOn = DateTime.Now;
        public DateTime? CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if (value != _CreatedOn)
                {
                    _CreatedOn = value;
                    Modified = true;
                }
            }
        }
        DateTime? _EditedOn = DateTime.Now;
        public DateTime? EditedOn
        {
            get { return _EditedOn; }
            set
            {
                if (value != _EditedOn)
                {
                    _EditedOn = value;
                    Modified = true;
                }
            }
        }
        string _EditedBy = "";
        public string EditedBy
        {
            get { return _EditedBy; }
            set
            {
                if (value != _EditedBy)
                {
                    _EditedBy = value;
                    Modified = true;
                }
            }
        }
        string _CreatedBy = "";
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if (value != _CreatedBy)
                {
                    _CreatedBy = value;
                    Modified = true;
                }
            }
        }

        public FiAccount.BusinessEntities.FiFiscalYear FiscalYear
        {
            get
            {
                return FiAccount.BusinessEntities.FiFiscalYear.GetItem(this.FiscalYearID);
            }
        }





        #endregion





        #region Constructors

        public FiChequeToFiTransactionItem()
        {
            Modified = false;
        }


        public FiChequeToFiTransactionItem(int keyFiChequeID)
        {
            this._fiChequeID = keyFiChequeID;
            // FillMyObject();
            Modified = false;
        }


        public FiChequeToFiTransactionItem(DAL.FiCheque fiCheque)
        {
            // Load(fiCheque);
        }

        #endregion
        #region Read Operation


        //load an existing Instance
        public void Load(int keyFiChequeID)
        {
            FiChequeID = keyFiChequeID;
            if (keyFiChequeID >= 0)
            {
                FillMyObject();
            }
            else
            {
                Load(null);
            }
            Modified = false;
        }


        //Add++ //DDL++
        public void Load(DAL.FiChequeToFiTransactionItem fiCheque)
        {
            if (fiCheque != null)
            {
                //this.FiChequeID = fiCheque.FiChequeID;

                //this.FiscalYearID = fiCheque.FiscalYearID;
                //this.ChequeNo = fiCheque.ChequeNo;
                //this.Bank = fiCheque.Bank;
                //this.MyBank = fiCheque.MyBank;
                //this.ValueDate = fiCheque.ValueDate;
                //this.Amount = fiCheque.Amount;
                //this.FiTransactionID = fiCheque.FiTransactionID;
                //this.Note = fiCheque.Note;
                //this.CurrencyID = fiCheque.CurrencyID;

                ////Default Fields                
                //this.CreatedBy = fiCheque.CreatedBy;
                //this.CreatedOn = fiCheque.CreatedOn;
                //this.EditedBy = fiCheque.EditedBy;
                //this.EditedOn = fiCheque.EditedOn;
                //this.Timestamp = fiCheque.TStamp;
                //this.StatusID = fiCheque.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);
            }
            else
            {
                //this.FiChequeID = -1;
                //this.FiscalYearID = -1;
                //this.ChequeNo = null;
                //this.Bank = String.Empty;
                //this.MyBank = String.Empty;
                //this.ValueDate = null;
                //this.Amount = 0;
                //this.FiTransactionID = null;
                //this.Note = String.Empty;
                //this.CurrencyID = null;

                ////Default Fields
                //this.CreatedBy = String.Empty;
                //this.EditedBy = String.Empty;
                //P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                //this.StatusID = initStatus.StatusID;
            }
            Modified = false;
        }



        #endregion

        internal P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();
            if (this.FiTransactionItemID < 0)
            {
                Load(this.FiTransactionItemID);
                return tMsg;
            }

            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (FiTransactionDataModelDataContext db = new FiTransactionDataModelDataContext(connectionString))
                {
                    var xElements = from xElement in db.FiChequeToFiTransactionItem
                                    where xElement.FiTransactionItemID == this.FiTransactionItemID
                                    select xElement;

                    foreach (var xElementx in xElements)
                    {
                        Load(xElementx);
                    }
                }

                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex)
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, this);
            }

            this.MessageStack.Add(tMsg);
            return tMsg;

        }
        #region Insert Operations
        public P2MessageStack InsertAndUpdate(P2MessageStack MessageStack, bool checkDoublicate, int fichequeid, int fitransactionid, int FiscalYearID, bool foradd)
        {
            MessageStack.AddRange(this.Validator.Validate(this));
            int isadded = 0;
            try
            {
                if (MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.green || MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.white || (MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.yellow && P2Validator.YellowErrorDialog.AskSave(MessageStack)))
                {
                    MessageStack.Clear();
                    if (this.FiTransactionItemID != null && this.FiTransactionItemID > 0)
                    {
                        // if FiTransactionID < -1 => unsaved item, store in temporary storage
                        var tempItem = TemporaryStorage.FirstOrDefault(it => it.FiTransactionItemID == this.FiTransactionItemID);
                        if (tempItem != null)
                        {
                            // existing item, do nothing
                        }
                        else
                        {
                            TemporaryStorage.Add(this);

                        }
                    }
                    else
                    {

                        string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);

                        using (FiTransactionDataModelDataContext db = new FiTransactionDataModelDataContext(connectionString))
                        {
                            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
                            {
                                //Add++ //DDL++ //--> Set it to starting status.
                                if (this.StatusID == -1) this.StatusID = 170501;

                                if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = User.Current.UserID;
                                this.EditedBy = User.Current.UserID;

                                DAL.FiChequeToFiTransactionItem editedItem;
                                if (foradd == true)
                                {

                                    if (fichequeid > 0 && fitransactionid > 0)
                                    {
                                        editedItem = new DAL.FiChequeToFiTransactionItem()
                                        {
                                            FiscalYearID = FiscalYearID,
                                            FiChequeID = fichequeid,

                                            FiTransactionItemID = fitransactionid,

                                            //Standard Fields                                      
                                            CreatedBy = this.CreatedBy,
                                            CreatedOn = DateTime.Now,
                                            EditedBy = this.EditedBy,
                                            EditedOn = DateTime.Now,


                                        };
                                        db.AddToFiChequeToFiTransactionItem(editedItem);
                                        isadded = 1;
                                    }
                                }
                                else
                                {
                                    editedItem = (from xItem in db.FiChequeToFiTransactionItem
                                                  where xItem.FiTransactionItemID == fitransactionid
                                                  select xItem).FirstOrDefault();

                                    if (editedItem != null)
                                    {
                                        if (editedItem.FiTransactionItemID > 0)
                                        {
                                            db.DeleteObject(editedItem);
                                            db.SaveChanges();
                                            ////Add++ //DDL++
                                            //editedItem.FiscalYearID = this.FiscalYearID;                                                           

                                            ////Standard Fields                                    

                                            isadded = 0;
                                        }
                                    }
                                    //editedItem.EditedBy = this.EditedBy;
                                    //editedItem.EditedOn = DateTime.Now;

                                }
                                if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red)
                                {
                                    db.SaveChanges();
                                    ts.Complete();
                                    if (this.FiChequeID < 0)
                                    {
                                        this.FiChequeID = fichequeid;
                                        this.FiTransactionItemID = fitransactionid;


                                    }
                                }
                            }
                        }

                        FillMyObject();
                    }
                    Modified = false;
                    if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red)
                    {
                        if (isadded == 1)
                        {
                            MessageStack.Add(new P2TransactionMessage("green", P2Translator.GetResource("TMsg_ChequeDetailsitemAdded")));
                        }
                        else
                            MessageStack.Add(new P2TransactionMessage("green", P2Translator.GetResource("TMsg_TMsg_ChequeDetailsitemAdded")));
                    }

                }
            }
            catch (Exception ex)
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, this);
            }
            return MessageStack;
        }

        #endregion










        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            Modified = true;
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        //Add++ //DDL++
        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("FiChequeID");

            OnPropertyChanged("FiscalYearID");
            OnPropertyChanged("ChequeNo");
            OnPropertyChanged("Bank");
            OnPropertyChanged("MyBank");
            OnPropertyChanged("ValueDate");
            OnPropertyChanged("Amount");
            OnPropertyChanged("FiTransactionID");
            OnPropertyChanged("Note");


            OnPropertyChanged("CurrencyID");


            //Standard Fields
            OnPropertyChanged("StatusName");
            OnPropertyChanged("StatusID");
        }

        #endregion


        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "FiChequeID", this);
                return _validator;
            }
        }

        #endregion
    }
}
